<template>
  <div>
    <div className="hello">
      <div style="height: 0px">
        <strong
          style="
            display: block;
            margin-top: 10px;
            text-align: center;
            font-size: 40px;
          "
          >分区预警</strong
        >
      </div>
      <div className="box">
        <div className="map">
          <div id="map" ref="map">
            <img style="width: 500px; height: 200px" src="" alt="无法显示" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { useStore } from "vuex";
import L from "leaflet";
import { onMounted, onUnmounted, ref, reactive, watch } from "vue";
import country from "@/assets/country.json"; //区级行政划分
import { getFQYJData } from "@/api/user/FQYJ";
import pako from "pako";

export default {
  name: "FQYJ",
  props: {
    totalData: {
      default: null,
    },
    selectSign: {
      default: null,
    },
  },
  mounted() {
    this.$emit("changeTimeIndex", 16);
    this.$emit("changeIsSelect2", false);
    this.$emit("changeIsSelect3", false);
    this.$emit("changeIsTimeOperator", true);
  },
  setup(props) {
    const totalData = reactive(props.totalData);
    const selectSign = ref(props.selectSign);

    watch(
      () => props.totalData,
      (newVal) => {
        console.log("totalData 发生了更改", newVal);
        totalData.value = newVal;
        params.year = newVal.getFullYear();
        params.month = newVal.getMonth() + 1;
        params.day = newVal.getDate();
        params.hour = newVal.getHours();
        params.minute = newVal.getMinutes();
        console.log("new params:", params);
        updateMap();
      },
      { deep: true }
    );

    watch(
      () => props.selectSign,
      (newVal) => {
        console.log("selectSign 发生了更改", newVal);
        selectSign.value = newVal;
        console.log(selectSign.value);
        updateMap();
      },
      { deep: true }
    );

    const store = useStore();
    let mymap;
    let geojsonLayer;
    let object = {
      user_id: store.state.userinfo.id,
      nums: 10,
    };

    let params = {
      year: 2023,
      month: 8,
      day: 20,
      hour: 10,
      minute: 0,
    };

    let warningType = [
      "台风预警",
      "暴雨预警",
      "高温预警",
      "雷雨大风预警",
      "雷电预警",
      "大风预警",
      "雷暴预警",
    ];

    const COLORS = ["blue", "yellow", "orange", "red"];

    onMounted(() => {
      initMap();
      updateMap();
    });
    onUnmounted(() => {
      if (mymap) {
        mymap.remove();
        mymap = null;
      }
    });

    async function initMap() {
      const guangdongCenter = [23.125178, 113.280637];
      mymap = L.map("map", { attributionControl: false }).setView(
        guangdongCenter,
        7
      );
      mymap.createPane('Pane2')
      mymap.getPane('Pane2').style.zIndex = 300
      
      const tileLayer1 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      const tileLayer3 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
          pane: "Pane2",
        }
      );
      // 添加默认底图
      tileLayer1.addTo(mymap);
      tileLayer3.addTo(mymap);

      // 设置地图缩放范围
      mymap.setMinZoom(4);
      mymap.setMaxZoom(10);

      //色标控件
      const legend = L.control({ position: "bottomright" });
      legend.onAdd = function (map) {
        const div = L.DomUtil.create("div", "legend");
        const grades = ["蓝色预警", "黄色预警", "橙色预警", "红色预警"];
        const colors = [];
        const labels = [];
        for (let i = 0; i < grades.length; i++) {
          let from = grades[i];
          colors.push(
            `<i style="background: ${COLORS[i]};width: 60px; height: 12px; float: left; opacity: 0.76;"></i>`
          );
          labels.push(
            `<i style="width: 60px; height: 30px; text-align: center; float: left; font-style: normal;">${from}</i>`
          );
        }
        div.innerHTML = `<div style="background-color: white; width: 250px; height: 60px; padding:5px">
                   <h3 style=" text-align: center;">预警等级</h3>
                   ${colors.join("") + "<br>" + labels.join("")}</div>`;
        return div;
      };
      legend.addTo(mymap);

      return mymap;
    }

    async function updateMap() {
      let data = await fetchData(params);
      console.log(data);

      if (data === null) {
        showTopMessage("当前时间没有相关数据", 2000);
      } else {
        //解压gzip
        const compressedData = data[0].data;
        // console.log(compressedData);
        const compressedUint8Array = Uint8Array.from(
          atob(compressedData),
          (c) => c.charCodeAt(0)
        );
        const uncompressedData = pako.inflate(compressedUint8Array);
        const decoder = new TextDecoder("utf-8");
        const decodedString = decoder.decode(uncompressedData);
        const geojson = JSON.parse(decodedString);
        // console.log(geojson);

        function getColor(feature) {
          const countryName = feature.properties.name;
          const matchingData = geojson.data.find(
            (obj) =>
              obj.class === warningType[selectSign.value] &&
              obj.District === countryName
          );

          if (matchingData) {
            const level = matchingData.level;
            // console.log(level);
            let fillColor = "white";

            switch (level) {
              case "1":
                fillColor = "white";
                break;
              case "2":
                fillColor = "blue";
                break;
              case "3":
                fillColor = "yellow";
                break;
              case "4":
                fillColor = "orange";
                break;
              case "5":
                fillColor = "red";
                break;
              default:
                fillColor = "white";
            }
            return {
              fillColor: fillColor,
              fillOpacity: 1,
              color: "#767676",
              weight: 1,
            };
          } else {
            return {
              fillColor: "white",
              fillOpacity: 1,
              color: "#767676",
              weight: 1,
            };
          }
        }
        mymap.createPane('Pane1')
        mymap.getPane('Pane1').style.zIndex = 250
        // 数据图层
        geojsonLayer = L.geoJSON(country, {
          style: getColor,
          pane: "Pane1",
        }).addTo(mymap);
      }
    }

    async function fetchData(params) {
      try {
        const Data = await getFQYJData(params); // 使用接口文件中的函数获取数据
        return Data;
      } catch (error) {
        console.error("Error fetching COO data:", error);
        return null;
      }
    }

    function showTopMessage(message, duration) {
      // 创建一个提示元素
      const messageElement = document.createElement("div");
      messageElement.className = "top-message";
      messageElement.textContent = message;

      // 将提示元素添加到页面的顶部
      document.body.appendChild(messageElement);

      // 设置定时器，在一定时间后自动隐藏提示
      setTimeout(() => {
        messageElement.style.opacity = "0"; // 渐变消失
        setTimeout(() => {
          document.body.removeChild(messageElement); // 删除提示元素
        }, 1000); // 在渐变结束后删除元素
      }, duration);

      // 自定义样式
      messageElement.style.position = "fixed";
      messageElement.style.top = "100px";
      messageElement.style.left = "42%";
      messageElement.style.width = "300px";
      messageElement.style.borderRadius = "4px";
      messageElement.style.backgroundColor = "#88bffa";
      messageElement.style.color = "#fff";
      messageElement.style.padding = "10px 0";
      messageElement.style.textAlign = "center";
      messageElement.style.transition = "opacity 1s ease-in-out";
    }

    return {
      totalData,
      selectSign,
    };
  },
};
</script>

<style scoped lang="scss">
.head-name {
  color: #b0e3ff;
  font-weight: bold;
  font-size: xx-large;
  padding: 50px;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
}

@media screen and (min-width: 700px) {
  .map {
    position: relative;
    border: 3px double #c7e8ff;
    background-color: #6c8fff;
    margin: 60px;
    width: 70%;
    height: 55vh;

    #map {
      width: 100%;
      height: 55vh;
      z-index: 1;
    }
    .img {
      position: absolute;
      bottom: 0;
      right: 0;
      z-index: 4;
    }
  }
}
</style>
